package com.taoyibao.hongcanting.ui.home.views;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.BaseRelativeLayout;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.event.EventUpdataCart;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.DishModel;
import com.taoyibao.hongcanting.model.SupplementModel;
import com.taoyibao.hongcanting.ui.home.activity.ChooseAddActivity;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * @author TangAnna
 * @description: 菜品数量控制器
 * @date :${DATA} 15:49
 */
public class CountControllerArea extends BaseRelativeLayout<DishModel> implements View.OnClickListener {
    private ImageView mIvAdd, mIvLess;
    private TextView mTvCount;
    private DishModel mDishModel;
    private String mSource;//用于判断操作的数据发送给谁处理  当mSource==CodeConstant.EVENT_SOURCE_MENU时需要选择菜品的口味
    /**
     * 用于判断是添加还是减少操作  -1减少   1添加
     */
    private int mAction = 0;

    public CountControllerArea(Context context) {
        super(context);
    }

    public CountControllerArea(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CountControllerArea(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void initView(Context context, AttributeSet attrs, int defStyleAttr) {
        mIvLess = findViewById(R.id.iv_count_controller_less);
        mIvAdd = findViewById(R.id.iv_count_controller_add);
        mTvCount = findViewById(R.id.tv_count_controller_count);
        mIvAdd.setOnClickListener(this);
        mIvLess.setOnClickListener(this);
    }

    @Override
    public void setData(DishModel data) {
        mDishModel = data;
        setCount();
    }

    @Override
    protected int bindLayout() {
        return R.layout.area_count_controller;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_count_controller_less://减少
                mAction = -1;
                getSupplement();
                break;
            case R.id.iv_count_controller_add://增多
                mAction = 1;
                getSupplement();
                break;
        }
    }

    /**
     * 判断当前菜品是否有可选参数
     */
    public void getSupplement() {
        if (TextUtils.equals(mSource, CodeConstant.EVENT_SOURCE_MENU)) {//菜单操作
            JsonApiWrapper.getApiService().getSupplement(SpUtils.getToken(), mDishModel.dish_code)
                    .compose(new DefaultTransformer<CompanyBaseModel<SupplementModel>>())
                    .subscribe(new ProgressSubscriber<CompanyBaseModel<SupplementModel>>(getContext(), true) {
                        @Override
                        public void onNext(CompanyBaseModel<SupplementModel> supplementModel) {
                            if (supplementModel.code == NetCode.HTTP_200) {
                                if (mAction == -1) {//减少
                                    ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintLess));
                                } else if (mAction == 1) {//添加
                                    ChooseAddActivity.open(getContext(), mDishModel, supplementModel.data);
                                }
                            } else if (supplementModel.code == NetCode.HTTP_7005) {//当前菜品没有可选择的口味直接添加
                                if (mAction == -1) {//减少
                                    lessDish();
                                } else if (mAction == 1) {//添加
                                    addDish();
                                }
                            } else {
                                super.onNext(supplementModel);
                            }
                        }
                    });
        } else if (TextUtils.equals(mSource, CodeConstant.EVENT_SOURCE_CART)) {//购物车操作 不需要判断是否有可选的属性直接增减
            if (mAction == -1) {//减少
                lessDish();
            } else if (mAction == 1) {//添加
                addDish();
            }
        }

    }

    /**
     * 添加菜品
     */
    public void addDish() {
        mDishModel.dish_count++;
        String class_code = "";
        if (!TextUtils.isEmpty(mDishModel.dish_classId)) {
            class_code = mDishModel.dish_classId;
        } else if (!TextUtils.isEmpty(mDishModel.class_code)) {
            class_code = mDishModel.class_code;
        }
        JsonApiWrapper.getApiService().cartAdd(SpUtils.getToken(), SpUtils.getMemberId(), class_code, mDishModel.class_name,
                mDishModel.dish_code, mDishModel.dish_pic, mDishModel.dish_name, "1",
                mDishModel.dish_unit, mDishModel.makeup, mDishModel.taste, mDishModel.dish_price + "",
                mDishModel.dish_discount_price + "")
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(getContext(), true) {
                    @Override
                    public void onNext(CompanyBaseModel updataCartModel) {
                        if (updataCartModel.code == NetCode.HTTP_200) {
                            ToastUtils.showToast("添加成功");
                            sendMessage();
                            setCount();
                        } else {
                            super.onNext(updataCartModel);
                        }

                    }
                });
    }

    /**
     * 减少菜品
     */
    public void lessDish() {
        mDishModel.dish_count--;
        JsonApiWrapper.getApiService().cartRemove(SpUtils.getToken(), SpUtils.getMemberId(), mDishModel.dish_code, "1", mDishModel.taste, mDishModel.makeup)
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(getContext(), true) {
                    @Override
                    public void onNext(CompanyBaseModel updataCartModel) {
                        if (updataCartModel.code == NetCode.HTTP_200) {
                            ToastUtils.showToast("删除成功");
                            sendMessage();
                            setCount();
                        } else {
                            super.onNext(updataCartModel);
                        }
                    }
                });
    }

    /**
     * 设置已经加入购物车商品数量
     */
    private void setCount() {
        if (mDishModel.dish_count == 0) {
            mTvCount.setVisibility(GONE);
            mIvLess.setVisibility(GONE);
        } else {
            mTvCount.setVisibility(VISIBLE);
            mIvLess.setVisibility(VISIBLE);
        }
        mTvCount.setText(mDishModel.dish_count + "");
    }

    /**
     * 设置数据来源
     * 购物车  还是菜单  主要作用是判断当前菜品是否要进行选择口味的操作
     *
     * @param source
     */
    public void setSource(String source) {
        mSource = source;
    }

    /**
     * 发送消息
     */
    public void sendMessage() {
        EventUpdataCart eventUpdataCart = new EventUpdataCart();
        eventUpdataCart.source = mSource;
        eventUpdataCart.action = mAction;
        eventUpdataCart.dishModel = mDishModel;
        EventBus.getDefault().post(eventUpdataCart);
    }
}
